package org.cjstudio.holypoopsgrs_interface.game.security;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class HolyPoopsSecurityUtils {
	
	public static String hash(String str) {
		try {
			// Create MD5 Hash
			MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
			digest.update(str.getBytes());
			byte messageDigest[] = digest.digest();
			
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			for (int i=0; i<messageDigest.length; i++){
				byte b = messageDigest[i];
				String hex = Integer.toHexString((int) 0x00FF & b);
				if (hex.length() == 1) {
					hexString.append("0");
				}
				hexString.append( hex );
				
//				hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
			}
			return hexString.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}
	
	protected static byte[] desEncrypt(byte[] plainText, byte[] rawKeyData) throws Exception {
		 DESKeySpec dks = new DESKeySpec(rawKeyData);  
		 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
		 SecretKey key = keyFactory.generateSecret(dks);  
		 Cipher cipher = Cipher.getInstance("DES");  
		 cipher.init(Cipher.ENCRYPT_MODE, key);  
		 byte data[] = plainText;  
		 byte encryptedData[] = cipher.doFinal(data);  
		 return encryptedData;  
	 }  
	  
	protected static byte[] desDecrypt(byte[] encryptText, byte[] rawKeyData) throws Exception {  
		 DESKeySpec dks = new DESKeySpec(rawKeyData);  
		 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
		 SecretKey key = keyFactory.generateSecret(dks);  
		 Cipher cipher = Cipher.getInstance("DES");  
		 cipher.init(Cipher.DECRYPT_MODE, key);  
		 byte encryptedData[] = encryptText;  
		 byte decryptedData[] = cipher.doFinal(encryptedData);  
		 return decryptedData;  
	 }  
	  
	 public static String encrypt(String input, String key) throws Exception {  
		 return base64Encode(desEncrypt(input.getBytes(), key.getBytes()));  
	 }  
	  
	 public static String decrypt(String input, String key) throws Exception {  
		 byte[] result = base64Decode(input);  
		 return new String(desDecrypt(result, key.getBytes()));  
	 }  
	  
	 protected static String base64Encode(byte[] s) {  
		 if (s == null) return null;  
		 return ReducedBase64.encodeBytes(s);  
	 }  
	  
	 protected static byte[] base64Decode(String s) throws IOException {  
		 if (s == null) return null;  
		 return ReducedBase64.decode(s); 
	 }
}
